package com.akk.business;


import com.akk.common.enums.UserCardEnums;
import com.akk.exception.RestBusinessException;
import com.akk.module.user.entity.User;
import com.akk.module.user.entity.UserCard;
import com.akk.module.user.model.request.AddUserCardRequest;
import com.akk.module.user.service.UserCardService;
import com.akk.utils.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserCardBusiness {

    @Autowired
    private UserCardService userCardService;


    public List<UserCard> userCards(String userId) {
        return userCardService.findByUserId(userId);
    }

    public boolean addCard(AddUserCardRequest request, User user) {
        if(userCardService.findByUserIdAndCardNum(user.getUserId(),request.getCardNum()).size() != 0){
            throw new RestBusinessException("该银行卡已存在，无需再次添加.");
        }
        UserCard userCard = new UserCard();
        userCard.setUserId(user.getUserId());
        userCard.setBankName(request.getBankName());
        userCard.setCardStatus(UserCardEnums.CardStatus.GENERAL.getValue());
        if(request.getCardType().equals(UserCardEnums.CardType.JIEJI.getValue())){
            userCard.setCardType(UserCardEnums.CardType.JIEJI.getValue());
        }else if(request.getCardType().equals(UserCardEnums.CardType.XINYONG.getValue())){
            userCard.setCardType(UserCardEnums.CardType.XINYONG.getValue());
            userCard.setCvv2(request.getCvv2());
            userCard.setMonth(request.getMonth());
            userCard.setYear(request.getMonth());
        }else{
            throw new RestBusinessException("卡类型错误.");
        }
        userCard.setCardId(IDUtils.getPK());
        userCard.setHoldName(user.getUsername());
        userCard.setCreateDate(new Date());
        userCard.setUpdateDate(new Date());
        userCard.setPhone(request.getBindPhone());
        userCard.setCardNum(request.getCardNum());
        userCardService.insert(userCard);
        return true;
    }

    public boolean delCard(String cardId) {
        UserCard userCard = userCardService.findByCardId(cardId);
        if(userCard.getCardStatus().intValue() == UserCardEnums.CardStatus.SETTLEMENT.getValue()){
            throw new RestBusinessException("默认结算卡不能删除.");
        }
        userCardService.delUserCard(userCard.getCardId());
        return true;
    }
}
